package config

import (
	"fmt"

	"gitee.com/terender/sfw/rlog"
	"gitee.com/terender/sfw/utils"

	"github.com/larspensjo/config"
)

var cfg *config.Config

// Read 读取config中配置的参数字段
func Read(v interface{}, section string, option string) error {
	switch p := v.(type) {
	case *string:
		s, err := cfg.String(section, option)
		if err != nil {
			return err
		}
		*p = s
	case *bool:
		b, err := cfg.Bool(section, option)
		if err != nil {
			return err
		}
		*p = b
	default:
		return fmt.Errorf(`fatal error: not supported type[%T] when read config file`, v)
	}
	return nil
}

var mapConfig = make(map[string]*config.Config)

// Get 返回制定名称的配置文件
func Get(file string) *config.Config {
	var cfg *config.Config
	cfg, ok := mapConfig[file]
	if !ok {
		runtime := `release`
		rc, err := config.ReadDefault(utils.ProjectPath() + `/config/runtime.ini`)
		if err != nil {
			rlog.Infof(`==== runtime.ini file not exist, using default [release]`)
		} else {
			runtime, err = rc.String(``, `runtime`)
			if err != nil {
				rlog.Errorf(`Error: runtime.ini file parse [%v]`, err)
				runtime = `release`
			}
		}
		path := utils.ProjectPath() + `/config/` + runtime + `/` + file
		rlog.Infof(`Read config file %v`, path)
		cfg, err = config.ReadDefault(path)
		if err != nil {
			rlog.Errorf(err.Error())
			return config.NewDefault()
		}
		mapConfig[file] = cfg
	}
	return cfg
}
